from google.appengine.api import users
from django.http import HttpResponse, HttpResponseRedirect
from radarwatch.radars import models
import forms
from django.shortcuts import render_to_response
from django.core import serializers
from django.template import Context, loader

def render(template, payload):
	payload['recents'] = models.Point.all().order('-created_on').fetch(5)
	return render_to_response(template, payload)

def index(request):
	user = users.get_current_user()
	logouturl = users.create_logout_url("/")
	loginurl = users.create_login_url("/")
	pointform = forms.PointForm()
	points = models.Point.all().order('-created_on').fetch(20)
	payload = dict(points = points,user=user, logouturl=logouturl, loginurl=loginurl, pointform=pointform)
	return render('radars/index.html', payload)

def create(request):
	if request.method == 'GET':
		pointform = forms.PointForm()
	if request.method == 'POST':
		pointform = forms.PointForm(request.POST)
		if pointform.is_valid():
			point = pointform.save()
			return HttpResponseRedirect("/")
	payload = dict(pointform=pointform)
	return render('radars/create.html', payload)

def directcreate(request):
	if request.method == 'GET':
		pointform = forms.PointForm(request.GET)
		if pointform.is_valid():
			point = pointform.save()
			return HttpResponse()
	return HttpResponse("An Error occurred")
		
def point_type(request, point_type):
	point = models.Point.all().filter('point_type = ', point_type)
	payload = dict(points = point)
	return render('radars/points_details.html', payload)

def contact(request):
	return render_to_response('radars/contact.html')
			
def returnPoints(request):
	points = models.Point.all().order('-created_on')
	payload = dict(points = points)
	# View code here...
	t = loader.get_template('radars/return_points.xml')
	c = Context(payload)
	r = HttpResponse(t.render(c), mimetype="text/xml")
	return r